package com.zyx.shiro;


import com.zyx.model.User;
import com.zyx.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

public class MyRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    public static final String SESSION_USER_KEY = "user";

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        User user = (User) SecurityUtils.getSubject().getSession().getAttribute(MyRealm.SESSION_USER_KEY);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRole(user.getRole().trim());
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        User user = tokenToUser((UsernamePasswordToken) token);
        User u = userService.getByNameAndPassword(user.getUsername(),user.getPassword());
        if(u!=null){
            // 设置session
            Session session = SecurityUtils.getSubject().getSession();
            session.setAttribute(MyRealm.SESSION_USER_KEY, u);
            Object principal = token.getPrincipal();
            return new SimpleAuthenticationInfo(principal, user.getPassword(), this.getName());
        }
        return null;
    }


    private User tokenToUser(UsernamePasswordToken authcToken) {
        User user = new User();
        user.setUsername(authcToken.getUsername());
        user.setPassword(String.valueOf(authcToken.getPassword()));
        return user;
    }
}
